//
//  KXP3DESCrypto.m
//  KXP-iOS
//
//  Created by sunPC on 2020/7/22.
//  Copyright © 2020 车开新. All rights reserved.
//

#import "KXCrypto3DES.h"
#import <CommonCrypto/CommonCryptor.h>
#import "GTMBase64.h"
#define gkey            @"NTMyMGM5NDQtY2ZkNy00MzVj"

@implementation KXCrypto3DES

// 加密
+ (NSString*)encrypt3DES:(NSString*)text key:(NSString *)key{
   return  [KXCrypto3DES crptyo:text operation:kCCEncrypt key:key];
}
// 解密
+ (NSString*)decrypt3DES:(NSString*)text key:(NSString *)key{
   return [ KXCrypto3DES crptyo:text operation:kCCDecrypt key:key];
}
+ (NSString*)crptyo:(NSString*)crptyoText
          operation:(CCOperation)operation
                key:(NSString*)key {
    
    
    size_t plainTextBufferSize;
    const void *vplainText;
    
    if (operation == kCCEncrypt) {
        
        NSData* data = [crptyoText dataUsingEncoding:NSUTF8StringEncoding];
        plainTextBufferSize = [data length];
        vplainText = (const void *)[data bytes];
    }else {
        
        NSData *encryptData = [GTMBase64 decodeData:[crptyoText dataUsingEncoding:NSUTF8StringEncoding]];
        
        plainTextBufferSize = [encryptData length];
        vplainText = [encryptData bytes];
    }
    
       CCCryptorStatus ccStatus;
       uint8_t *bufferPtr = NULL;
       size_t bufferPtrSize = 0;
       size_t movedBytes = 0;
    
       bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
       bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
       memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
       const void *vkey = (const void *) [key UTF8String];
       
       ccStatus = CCCrypt(operation,
                          kCCAlgorithm3DES,
                          kCCOptionECBMode|kCCOptionPKCS7Padding, //设置模式
                          vkey, //"123456789012345678901234", //key
                          kCCKeySize3DES,
                          nil, //"init Vec", //iv,
                          vplainText, //"Your Name", //plainText,
                          plainTextBufferSize,
                          (void *)bufferPtr,
                          bufferPtrSize,
                          &movedBytes);

    
    NSString *result;
    if (operation == kCCEncrypt) {
        NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
        result = [GTMBase64 stringByEncodingData:myData];
    }else {
        NSData *data = [NSData dataWithBytes:(const void *)bufferPtr
                                      length:(NSUInteger)movedBytes];
        result = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding] ;
    }
    return result;
    
}
@end
